package com.lwlk.util.reflact;

import com.lwlk.util.flow.Try;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


// 类型工具类
public class ClassInfo {

    private static List<String> flattenClasses(Class<?> clazz, List<String> classes) {
        if (clazz == null) return classes;
        String className = clazz.getName();
        if (classes.contains(className)) {
            return classes;
        } else {
            return flattenClasses(clazz.getSuperclass(), classes.add(className) ? classes : classes);
        }
    }

    // 获得某个类型的继承链
    public static <T> List<String> itClasses(T var) {
        return flattenClasses(var.getClass(), new ArrayList<>());
    }

    // 获得某个类型的直接接口链
    public static <T> List<String> itInterfaces(T var) {
        Stream<String> classStream = itClasses(var).stream();
        Stream<Class<?>> interfaceStream = classStream.flatMap((name) ->
                Stream.of(Try.ignoreGet(() -> Class.forName(name).getInterfaces()).orElse(new Class<?>[0])));
        return interfaceStream.distinct().map(Class::getName).collect(Collectors.toList());
    }

    public static void main(String[] args) {

        itClasses(new ArrayList()).forEach(System.out::println);

        System.out.println("---");

        itInterfaces(new ArrayList()).forEach(System.out::println);
    }
}
